package com.lei.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.lei.entity.Staff;
import com.lei.service.StaffService;
import com.lei.service.impl.StaffServiceImpl;
import com.lei.util.MyResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Lei Chu
 * @Date 2020/10/21 12:06
 */
@WebServlet("/fileServlet/*")
@MultipartConfig
public class FileServlet extends BaseServlet {

    private final StaffService staffService = new StaffServiceImpl();
    private final MyResult myResult = new MyResult();

    public String avatarUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //layui默认文件上传参数名叫做file
        Part part = request.getPart("file");
        //获取上传的文件名
        String disposition = part.getHeader("Content-Disposition");
        //从文件名截取后缀
        String suffix = disposition.substring(disposition.lastIndexOf("."), disposition.length() - 1);
        //获取随机码
        UUID uuid = UUID.randomUUID();
        //将随机码和后缀拼接，组成的新的文件名
        String objectName = uuid + suffix;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = "LTAI4FzJP8kBb76TmBqQ8BDo";
        String accessKeySecret = "lcFxxcnZrGnZgeHTakworrRKWpnW1v";
        String bucketName = "aaachenjian";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        InputStream inputStream = part.getInputStream();
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();

        //https://aaachenjian.oss-cn-beijing.aliyuncs.com/cd725c68-8c3b-4363-a85b-403311e401b7.jpg
        myResult.setData("https://" + bucketName + "." + endpoint + "/" + objectName);
        // 从session中取出当前用户
        HttpSession session = request.getSession();
        Staff nowStaff = (Staff) session.getAttribute("nowStaff");

        int i =staffService.updateUrl(myResult.getData(),nowStaff.getId());
        if (i>0){
            //头像   更改
            nowStaff.setUrl(myResult.getData());
            myResult.setCode(0);
        }

        return JSON.toJSONString(myResult);
    }

}

